#include "Common.hpp"

class ShareMemory
{
private:
    bool CreateShmHelper(int flag)
    {
        _key = ::ftok(gpath.c_str(), gprojId);
        if (_key < 0)
        {
            std::cerr << "ftok error" << std::endl;
            return false;
        }
        std::cout << "ftok key:" << _key << std::endl;
        // 由服务端创建新共享内存
        _shmid = ::shmget(_key, gshmsize, flag);
        if (_shmid < 0)
        {
            std::cerr << "shmget error" << std::endl;
            return false;
        }
        std::cout << "shmget success shmid=" << _shmid << std::endl;
        return true;
    }

public:
    ShareMemory() 
    : _addr(nullptr),_shmid(-1)
    {
    }
    bool CreateShm()
    {
        return CreateShmHelper(IPC_CREAT | IPC_EXCL | gmode);
    }
    bool GetShm()
    {
        return CreateShmHelper(IPC_CREAT | gmode);
    }
    bool AttachShm()
    {
        _addr = shmat(_shmid, nullptr, 0);
        if ((long long)_addr == -1) // 挂接失败，共享内存也是有权限的
        {
            std::cerr << "shmat error" << std::endl;
            return false;
        }
        std::cout << "shmat success addr=" << _addr << std::endl;
        return true;
    }
    bool DetachShm()
    {
        if (_addr == nullptr)
            return false;
        int n = shmdt(_addr);
        if (n < 0)
        {
            std::cerr << "shmdt error" << std::endl;
            return false;
        }
        std::cout << "shmdt success addr=" << _addr << std::endl;
        return true;
    }
    bool DeleteShm()
    {
        if(_shmid == -1)return false;
        // 回收创建的共享内存
        shmctl(_shmid, IPC_RMID, nullptr);
        std::cout << "ipcrm success shmid=" << _shmid << std::endl;
        return true;
    }

    void* GetAddr()
    {
        return _addr;
    }

    ~ShareMemory()
    {
    }

private:
    int _shmid;
    key_t _key;
    void *_addr;
}share_mem;